/****** 定义常量 ******/
var machineHead = ['名称','状态','类型','操作'];
var hostTH = ['名称','用户名','操作'];
var $filterSelect = $('#auth-table .table-filter select');
var $filterSearch = $('#auth-table .search');
var filters = {
	  	'用户名':'name',
	  	'虚拟机名':'vmName',
  	};
$('.back-page').click(function(e){
	e.stopPropagation();
	e.preventDefault();
	window.location.href = CTX_PATH+'/console/node';
})

$.fn.datetimepicker.dates['zh'] = {
	    days: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
	    daysShort: ["日", "一", "二", "三", "四", "五", "六", "七"],
	    daysMin: ["日", "一", "二", "三", "四", "五", "六", "七"],
	    meridiem:["早上","下午"],
	    months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
	    monthsShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],	    
	    today: "今天"
};
var machineChart;
/**
 * 云节点信息 - 总览标签页组件
 */
var NodeInfoOverViewTab = React.createClass({
	
    getInitialState: function () {  
        return {
        	name:'--',
        	addr:'--',
    		nodeType:'--',
        	machines:'--',
        	hostTotal:'--',
        	hostRunning:'--',
        	termTotal:'--',
        	termLinking:'--',
        	sumLogin:'--',
        	nowLogin:'--',
        };  
    },
	render : function(){
	
		var services = [];
		if(this.state.services != null && this.state.services.length > 0){
			for(var i in this.state.services){
				var tmp = this.state.services[i];
				var state;
				
				switch(tmp.state){
				case -1:
					state = <span className="badge danger">停止</span>;
					break;
				case 1:
					state = <span className="badge success">运行</span>;
					break;
				case 2:
					state = <span className="badge ">未知</span>;
					break;
				}
				services.push( <li className='list-group-item'>{tmp.name}  {state}</li>);
			}
		}else{
			services = '暂无服务'
		}
		return <div className='node-info-tab'>
				<div className='row'>

					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>基本信息</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>名称：{this.state.name}</li>
						    <li className='list-group-item'>地址：{this.state.addr}</li>
						  </ul>
						</div>
					</div>
					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>用户</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>累计登陆数：{this.state.sumLogin}</li>
						    <li className='list-group-item'>当前在线：{this.state.nowLogin}</li>
						  </ul>
						</div>
					</div>
				</div>
				<div className='row'>
					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>资源池</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>类型：{this.state.nodeType}</li>
						    <li className='list-group-item'>机器数：{this.state.machines}</li>
						  </ul>
						</div>
					</div>
					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>云电脑</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>已创建：{this.state.hostTotal}</li>
						    <li className='list-group-item'>运行中：{this.state.hostRunning}</li>
						  </ul>
						</div>
					</div>
					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>云终端</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>已授权：{this.state.termTotal}</li>
						    <li className='list-group-item'>连接中：{this.state.termLinking}</li>
						  </ul>
						</div>
					</div>
				</div>
				<div className="row">
					<div className='col-md-4'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>系统服务</div>
						  <ul className='list-group'>
						    {services}
						  </ul>
						</div>
					</div>	
				</div>
			</div>;
	}
});
/**
 * 云节点信息 - 资源池标签页组件
 */
var machineTrRatios = [4,4,4];
var NodeResourcePoolTab = React.createClass({
    getInitialState: function () {  
        return {
        	memEvaln:'--',
        	diskEvaln:'--',
        	disk:{
        		free:0,
        		used:null,
        		unit:''
        	},
        	memory:{
        		free:0,
        		used:null,
        		unit:''
        	},
        	machines:[]
        };  
    },
    componentDidMount:function(){
    	$('.layer-tip').mouseover(function(){
    		layer.tips($(this).attr('data-tip'), $(this));
    	});
    },
    componentDidUpdate  : function(){
        
        var $table = $(this.refs.table);
        $table.find("[data-toggle='tooltip']").tooltip();
        
    	var memoryChart = echarts.init(this.refs.memoryChart);
    	var diskChart = echarts.init(this.refs.diskChart);
    	var memoryChartOption = {
    		    tooltip : {
    		        trigger: 'item',
    		        formatter: '{a} <br/>{b} : {c}'+this.state.memory.unit+' ({d}%)'
    		    },
    		    series : [
    		        {
    		            name: '内存',
    		            type: 'pie',
    		            radius : '70%',
    		            center: ['50%', '50%'],
    		            data:[
    		                {value:this.state.memory.used, name:'已使用'},
    		                {value:this.state.memory.free, name:'剩余'},
    		            ],
    		            itemStyle: {
    		                emphasis: {
    		                    shadowBlur: 10,
    		                    shadowOffsetX: 0,
    		                    shadowColor: 'rgba(0, 0, 0, 0.5)'
    		                }
    		            }
    		        }
    		    ]
    		};
    	var diskChartOption = {
    		    tooltip : {
    		        trigger: 'item',
    		        formatter: '{a} <br/>{b} : {c} '+this.state.memory.unit+' ({d}%)'
    		    },
    		    series : [
    		        {
    		            name: '磁盘',
    		            type: 'pie',
    		            radius : '70%',
    		            center: ['50%', '50%'],
    		            data:[
    		                {value:this.state.disk.used, name:'已使用'},
    		                {value:this.state.disk.free, name:'剩余'},
    		            ],
    		            itemStyle: {
    		                emphasis: {
    		                    shadowBlur: 10,
    		                    shadowOffsetX: 0,
    		                    shadowColor: 'rgba(0, 0, 0, 0.5)'
    		                }
    		            }
    		        }
    		    ]
    		};
		// 生成内存使用饼图
    	memoryChart.setOption(memoryChartOption);
		
		// 生成磁盘使用饼图
    	diskChart.setOption(diskChartOption);
    },
	render : function(){
		var rows = null;
		var machines = this.state.machines ;
		if(machines != null){
			rows = [];
			for(var i in machines){
				rows.push(<NodeMachineTableTr name={machines[i].name} type={machines[i].type} id={machines[i].id}></NodeMachineTableTr>);
			}
		}
		var machineTable = <TeOpsTable title='机器列表' heads={machineHead} ratios={machineTrRatios}  paging={false} rows={rows}></TeOpsTable>;
		return <div className='node-info-tab'>
				<div className='row'>
					<div className='col-md-7'>
						<div className='col-md-5 col-md-offset-1'>
						   <div  className='col-md-12'>
							   <div ref='memoryChart' className='pool-chart1'>
							   </div>
						   </div>
						   <div  className='col-md-12 pool-chart1-title'>
							   内存
						   </div>
						</div>
						<div className='col-md-5 col-md-offset-1'>
							<div  className='col-md-12'>
							   <div ref='diskChart' className='pool-chart1'>
							   </div>
						   </div>
						   <div  className='col-md-12 pool-chart1-title'>
						   	   磁盘 <span className='icon-question-sign layer-tip'    data-tip='提示:统计所有机器下 "/" "/adminpool" "/userpool" "fileserver" 目录 '></span>
						   </div>
						</div>
					</div>
					<div className='col-md-5'>
						<div className='panel panel-default'>
						  <div className='panel-heading'>状态评估</div>
						  <ul className='list-group'>
						  	<li className='list-group-item'>内存：{this.state.memEvaln}</li>
						    <li className='list-group-item'>磁盘：{this.state.diskEvaln}</li>
						  </ul>
						</div>
					</div>
				</div>
				<div className='row'>
					<div className='col-md-10 col-md-offset-1' ref='table'>
						{machineTable}
					</div>
				</div>
			   </div>;
	}
});

var HostTab = React.createClass({
	componentDidMount:function(){
		if(hostTable == null){
			initHostTable();
		}else{
			//加载数据
		}
	}, 
	render:function(){
		return <div id= 'node-host-table'>
					
			  	</div>
	}
});
//重启虚拟机
var HostTableTrOperationGroup = React.createClass({
	restart:function(){
		// 重启虚拟机
		$.ajax({
			url:CTX_PATH+'/console/detail/host/restart',
			type:'post',
			data:{
				token:$.cookie('token'),
				hostName:this.props.hostName,
				hostId:nodeId[0]
			},
			success:function(rtn){
				console.log('host restart data:%o',rtn)
				if(!rtn.error){
					layer.msg('重启云电脑发送成功')
				}else{
					layer.msg('重启云电脑发送失败');
					console.error(rtn.msg);
				}
			}
		})
	},
	link:function(){
		//TODO 连接虚拟机
		alert('连接云电脑 '+this.props.nodeId)
	},
	render:function(){
		return <div className='btn-group'>
		        <button type='button' onClick={this.restart} className='btn btn-default'>重启</button>
		      </div>;
	}
});
/**
 * 节点机器列表 - 行组件
 */
var NodeMachineTableTr = React.createClass({
    getInitialState: function() {
        return{
            time : null
        }
      },
	componentDidMount:function(){
        
		//加载最新机器cpu和内存数据
    	$.ajax({
    		url:CTX_PATH+'/console/node/detail/machine/state',
    		type:'post',
    		data:{
    			token:$.cookie('token'),
    			hostId:nodeId[0]
    		},
    		success:function(rtn){
    			console.log('machine states:%o',rtn);
    			if(!rtn.error){
    				var data = rtn.data;
    				if(data != null && data.length > 0){
    					for(var i in data){
    						var state = data[i];
    						var newTime=state.updateTime;
    						if(newTime == null){
    						    var time = '--';
    						}else{
    						    var time = getUpdateTime(newTime);
    						}
    						if(state.cpu == null && state.memory == null){
        						$('#m-cpu-'+state.machineId).html('CPU:'+'--');
        						$('#m-memory-'+state.machineId).html('内存:'+'--');
    						}else{
    						    $('#m-cpu-'+state.machineId).html('CPU:'+state.cpu.toFixed(2)+'%').attr('title',time).tooltip('fixTitle');
                                $('#m-memory-'+state.machineId).html('内存:'+(state.memory/1073741824).toFixed(2)+'GB').attr('title',time).tooltip('fixTitle');
    						}
    						
    					}
    				}
    			}else{
    				
    			}
    		}
    	})
	},
	render:function(){
	    var updateTime = this.state.time;
		var operationComp = <NodeMachineTableTrOperationGroup id={this.props.id} name={this.props.name}></NodeMachineTableTrOperationGroup>;
		var type = '--';
		if(this.props.type != null){
			type = this.props.type;
		}
		var state = <div> <span id={'m-cpu-'+this.props.id} data-toggle='tooltip' className="label label-success">CPU:-</span> <span id={'m-memory-'+this.props.id} data-toggle='tooltip' className="label label-success">内存:-</span> </div>
		return <tr className='machine-tr'>
					<td >{this.props.name}</td>
					<td >{state}</td>
					<td >{type}</td>
					<td>{operationComp}</td>
			  </tr>;
	}
});
/**
 * 节点机器列表 - 操作按钮组件
 */
var NodeMachineTableTrOperationGroup = React.createClass({
	showCpuLoad:function(){
		showMachineChart(this.props.name,'CPU负载（1min 5min 15min）');
		machinePanel.setState({
			drawChart:drawCpuloadChart,
			id:this.props.id
		});
	},
	showMemory:function(){
		showMachineChart(this.props.name,'内存使用');
		machinePanel.setState({
			drawChart:drawMemoryUsageChart,
			id:this.props.id
		});
	},
	showNet:function(){
		showMachineChart(this.props.name,'网络');
		machinePanel.setState({
			drawChart:drawNetTrafficChart,
			id:this.props.id
		});
	},
	showDiskRoot:function(){
		showMachineChart(this.props.name,'磁盘(目录：/)');
		machinePanel.setState({
			drawChart:drawDiskRootChart,
			id:this.props.id
		});
	},
	showDiskBoot:function(){
		showMachineChart(this.props.name,'磁盘(目录：/boot)');
		machinePanel.setState({
			drawChart:drawDiskBootChart,
			id:this.props.id
		});
	},
	showDiskAdminPool:function(){
		showMachineChart(this.props.name,'磁盘(目录：/adminpool)');
		machinePanel.setState({
			drawChart:drawDiskAdminPoolChart,
			id:this.props.id
		});
		
	},
	showDiskUserPool:function(){
		showMachineChart(this.props.name,'磁盘(目录：/userpool)');
		machinePanel.setState({
			drawChart:drawDiskUserPoolChart,
			id:this.props.id
		});
	},
	showDiskFileServer:function(){
		showMachineChart(this.props.name,'磁盘(目录：/fileserver)');
		machinePanel.setState({
			drawChart:drawDiskFileServerChart,
			id:this.props.id
		});
	},
	render:function(){
		var name = this.props.name;
		var type = '2';
		return <div className='btn-group'>
		        <div className='btn-group'>
		          <button type='button' className='btn btn-default dropdown-toggle' data-toggle='dropdown'>
		            图表
		            <span className='caret'></span>
		          </button>
		          <ul className='dropdown-menu pull-right'>
		            <li><a href='#' onClick={this.showCpuLoad}>cpu负载</a></li>
		            <li><a href='#' onClick={this.showMemory}>内存</a></li>
		            <li><a href='#' onClick={this.showNet}>网络</a></li>
		            <li><a href='#' onClick={this.showDiskRoot} >磁盘(目录: /)</a></li>
		            <li><a href='#' onClick={this.showDiskBoot} >磁盘(目录: /boot)</a></li>
		            <li><a href='#' onClick={this.showDiskAdminPool} >磁盘(目录: /adminpool )</a></li>
		            <li><a href='#' onClick={this.showDiskUserPool} >磁盘(目录: /userpool )</a></li>
		            <li><a href='#' onClick={this.showDiskFileServer} >磁盘(目录: /fileserver )</a></li>
		          </ul>
		        </div>
		      </div>
		     ;
	}
});
/**
 * 机器图表面板组件
 */		           
var MachineChartPanel = React.createClass({
	 getInitialState: function () {  
	        return {
	        	drawChart:null,
	        	id:null
	        };  
	},
	componentDidMount:function(){
	    var $searchInfo = $(this.refs.searchInfo);
        $searchInfo.find("[data-toggle='tooltip']").tooltip();
		var _this = this;
		var $beginTime = $(this.refs.beginTime);
		var $endTime = $(this.refs.endTime);
		var $beginTimeVal = $(this.refs.beginTimeVal);
		var $endTimeVal = $(this.refs.endTimeVal);
		var $search = $(this.refs.search);
		var endDate = new Date();
		var startDate = new Date();
		startDate.setDate(startDate.getDate() - 6);
		$beginTime.datetimepicker({
			    language:"zh",
		        format: "yyyy-mm-dd hh:ii",
		        autoclose: true,
		        todayBtn: true,
		        pickerPosition: "bottom-left",
		        startView: 'month',
		        minView:'hour',
		        endDate:endDate, //只显示到今天之前的
		        startDate:startDate
		 }).on('changeDate', function(ev){//时间控件时间改变触发的事件
			 $beginTimeVal.val(ev.date.valueOf());
			 console.log(new Date(ev.date.valueOf()))
		 });
		$endTime.datetimepicker({
			    language:"zh",
		        format: "yyyy-mm-dd hh:ii",
		        autoclose: true,
		        todayBtn: true,
		        pickerPosition: "bottom-left",
		        startView: 'month',
		        minView:'hour',
		        endDate:endDate,//只显示到今天之前的
		        startDate:startDate
		 }).on('changeDate', function(ev){//时间控件时间改变触发的事件
			 $endTimeVal.val(ev.date.valueOf());
			 console.log(new Date(ev.date.valueOf()))
		 });
		$search.click(function(){
			var beginTime = $beginTimeVal.val();
			var endTime = $endTimeVal.val();
			if( beginTime != null && endTime != null && beginTime > endTime){
				layer.msg('结束时间不能早于开始时间');
			}else {
				if(_this.state.drawChart != null){
					_this.state.drawChart(_this.state.id,beginTime,endTime);
				};
			}
		});
	},
	render:function(){
		return 	<div className='row'>
					<div className='col-md-12 machine-chart-bar' ref='searchInfo'> 
						<form className='form-inline'>
						  <div className='form-group'>
						  	<input type='hidden' ref='beginTimeVal' className='form-control' />
						    <input type='text' ref='beginTime' className='form-control' readOnly='readonly' /> 
						  </div>
						  <span>到</span>
						  <div className='form-group'>
						  	<input type='hidden' ref='endTimeVal' className='form-control' />
						    <input type='text' ref='endTime' className='form-control' readOnly='readonly'/>
						  </div>
						  <span></span>
						  <a className='btn-glow primary' ref='search'>查询</a><span className='icon-question-sign layer-tip' data-toggle='tooltip' data-placement='right' title='只能查询从今天开始 七天以内的数据'></span>
						</form>
					</div>
					<div className='col-md-12 machine-chart-view'> 
					</div>
				</div>;
	}
});		            
var ComingSoonTab = React.createClass({
	render:function(){
		return <div className='coming-soon'>
				<h1>马上到来，敬请期待！</h1>
				</div>;
	}
});         
var HostTableTr = React.createClass({
	render:function(){
  		var operationComp = <HostTableTrOperationGroup hostName={this.props.vmName} ></HostTableTrOperationGroup>
  		return <tr className='teops-tr'>
  					<td>{this.props.vmName}</td>
  					<td>{this.props.userName}</td>
  					<td>{operationComp}</td>
  			  </tr>;
  	}
});		            
var nodeInfoTabs = [];
nodeInfoTabs.push({
	id:'node-info-overview',
	name:'总览',
	active:true,
	loadData:getOverView
	
},{
	id:'node-info-resource-pool',
	name:'资源池',
	icon:'iconfont icon-resource-pool',
	loadData:getResourcePool
},{
	id:'node-info-host',
	name:'云电脑',
	icon:'iconfont icon-cloud-host',
	loadData:getHost
},
//{
//	id:'node-info-termianl',
//	name:'云终端',
//	icon:'iconfont icon-box',
//},
{
	id:'node-info-user',
	name:'登陆用户',
	icon:'icon-user',
});
var nodeInfo = ReactDOM.render(
		<TeOpsTab tabs={nodeInfoTabs}></TeOpsTab>,
		 document.getElementById('node-info')
);
var overviewTab = ReactDOM.render(
		<NodeInfoOverViewTab></NodeInfoOverViewTab>,
		 document.getElementById('node-info-overview')
);
var resourcePoolTab = ReactDOM.render(
		<NodeResourcePoolTab></NodeResourcePoolTab>,
		 document.getElementById('node-info-resource-pool')
); 
		
var machinePanel = ReactDOM.render(
		<MachineChartPanel></MachineChartPanel>,
		document.getElementById('machine-chart')
);
var hostTab = ReactDOM.render(
		<HostTab></HostTab>,
		 document.getElementById('node-info-host')
);
//var termianlTab = ReactDOM.render(
//		<ComingSoonTab></ComingSoonTab>,
//		 document.getElementById('node-info-termianl')
//); 
var userTab = ReactDOM.render(
		<ComingSoonTab></ComingSoonTab>,
		 document.getElementById('node-info-user')
); 
/******方法*******/
var hostTable;
function initHostTable(){
	var barComp = [
  		<TeOpsTableFilter filters={filters} ></TeOpsTableFilter>,
   		<TeOpsTableSearch placeholder='搜索关键字...' enterCall={searchHostCall} ></TeOpsTableSearch>,
  		<TeOpsTableBtn name='搜索' type='primary' icon='icon-search'  click={searchHost}></TeOpsTableBtn>,
  		<TeOpsTableBtn name='重置' type=''   click={resetHostTable}></TeOpsTableBtn>
  	];
  	hostTable = ReactDOM.render(
  			<TeOpsTable title='节点云主机' heads={hostTH}  paging={true} loadData={getHost} barCompnents={barComp}></TeOpsTable>,
  			document.getElementById('node-host-table')
  	);

  	getHost(null,1,10);
}

function getHost(keyWords,pn,ps){
	var vmName,name;
	if(keyWords != null){
		name = keyWords.name;
		vmName = keyWords.vmName;
	}
	var loading = layer.load(1, {
	  shade: [0.5,'#fff'] //0.1透明度的白色背景
	});
	$.ajax({
		url : CTX_PATH + '/console/detail/host/page',
		type:'post',
		data :{
			token:$.cookie('token'),
  			name:name,
  			pageSize:ps,
  			pageNum:pn,
  			hostId:nodeId[0],
  			vmName:vmName
		},
		success:function(rtn){
		console.log('host data:%o',rtn)
			if(!rtn.error){
				var data = rtn.data;
				var list = data.list;
				var pn = data.pageNum;
				var ps = data.pageSize;
				var total = data.total;
				var hostId = data.nodeId;
				var vmName = data.vmName;
				var userName = data.userName;
				var rows = [];
				for(var i in list){
					var r = list[i];
					rows.push(<HostTableTr vmName={r.vmName} userName={r.userName} ></HostTableTr>);
				}
				hostTable.setState({ 
					'keyWords':{
						vmName:vmName,
  						name:name
					},
					'rows':rows,
					'pageNum':pn,
					'pageSize':ps,
					'total':total
				});
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
			layer.close(loading)
		},
		error:function(){
			layer.close(loading)
		}
	
	});
	
}
function searchHostCall(val){
	//搜索框搜索
	var initData = hostTable.getInitialState();
	var keyWords = initData.keyWords;
	var key = $('#node-host-table .table-filter select').val();
	keyWords[key] = val;
	getHost(keyWords,initData.pageNum,initData.pageSize);
}
function searchHost(){
	var val = $("#node-host-table .search").val();
	searchHostCall(val);
}
function resetHostTable(){
	//重置表格，并重新加载
	var initData = hostTable.getInitialState();
	getHost(initData.keyWords,initData.pageNum,initData.pageSize);
	$("#node-host-table .search").val("");
}

function getOverView(){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	$.ajax({
		url : CTX_PATH + '/console/node/detail/overview',
		type:'post',
		data : {
			token : $.cookie('token'),
			hostId : nodeId[0],
		},
		success : function(rtn){
			console.log(rtn)
			if(!rtn.error){
				var data = rtn.data;
				var name = data.name == null ? '--':data.name;
				var addr = data.addr == null ? '--':data.addr;
				var nodeType = data.pool.type == null ? '--':data.pool.type;
				var machines = data.pool.machines == null ? '--':data.pool.machines;
				
				var hostTatol = data.host.total == null ? '--':data.host.total;
				var hostRunning = data.host.running == null ? '--':data.host.running;
				var hostLinking = data.host.linking == null ? '--':data.host.linking;
				
				var termTotal = data.termianl.total == null ? '--':data.termianl.total;
				var termLinking = data.termianl.linking == null ? '--':data.termianl.linking;
				
				var sumLogin = data.user.sum == null ? '--':data.user.sum;
				var nowLogin = data.user.online == null ? '--':data.user.online;
				overviewTab.setState({
					name:name,
					addr:addr,
		    		nodeType:nodeType,
		        	machines:machines,
		        	hostTotal:hostTatol,
		        	hostRunning:hostRunning,
		        	hostLinking:hostLinking,
		        	termTotal:termTotal,
		        	termLinking:termLinking,
		        	sumLogin:sumLogin,
		        	nowLogin:nowLogin,
		        	services:data.services,
				});
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
			layer.close(loading)
		},
		error:function(){
			layer.close(loading)
		}
	});
}
/**
 * 获取机器列表状态更新时间
 */
function getUpdateTime(time){
    var result = "";
    var minute = 60;
    var hour = minute * 60;
    var now = Math.round(new Date().getTime()/1000).toString();
    var diffValue = now - time; 
    if(diffValue < 0){}
    var hourC =diffValue/hour;
    var minC =diffValue/minute;
    var sec = diffValue;
    if(hourC>=1){
        result=parseInt(hourC) +"个小时前";
    }
    else if(minC>=1){
    	result=parseInt(minC) +"分钟前";
    }else if(sec>0 && sec <=59){
        result=parseInt(sec) +"秒前";
    }
    return result;
}
/**
 * 获取资源池数据
 */
function getResourcePool(){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	$.ajax({
		url : CTX_PATH + '/console/node/detail/pool',
		type:'post',
		data : {
			token : $.cookie('token'),
			hostId : nodeId[0],
		},
		success:function(rtn){
			
			console.log('detail pool data:%o',rtn);
			if(!rtn.error){
				var data = rtn.data;
				
				// 生成评价
				var memEvaln = '--';
				var diskEvaln = '--';
				// 生成机器列表
				var fixed = 2;
				var memFree = 0;
				if(data.memory.total != null && data.memory.used != null){
					memFree = data.memory.total - data.memory.used;
					memFree = memFree.toFixed(fixed);
				}
				if(data.memory.total != null){
					data.memory.total = data.memory.total.toFixed(fixed);
				}
				if( data.memory.used != null){
					data.memory.used = data.memory.used.toFixed(fixed);
				}
				var diskFree = 0;
				if(data.disk.total != null && data.disk.used != null){
					diskFree = data.disk.total - data.disk.used;
					diskFree = diskFree.toFixed(fixed);
				}
				if(data.disk.total != null){
					data.disk.total = data.disk.total.toFixed(fixed);
				}
				if( data.disk.used != null){
					data.disk.used = data.disk.used.toFixed(fixed);
				}
				
				switch(data.evaluation.diskState){
				case 1:
					diskEvaln = '空闲';
					break;
				case 2:
					diskEvaln = '正常';
					break;
				case 3:
					diskEvaln = '不足';
					break;
				}
				
				switch(data.evaluation.memoryState){
				case 1:
					memEvaln = '空闲';
					break;
				case 2:
					memEvaln = '正常';
					break;
				case 3:
					memEvaln = '不足';
					break;
				}
				
				
				resourcePoolTab.setState({
		        	memEvaln:memEvaln,
		        	diskEvaln:diskEvaln,
		        	disk:{
		        		free:diskFree,
		        		used:data.disk.used,
		        		unit:data.disk.unit
		        	},
		        	memory:{
		        		free:memFree,
		        		used:data.memory.used,
		        		unit:data.memory.unit
		        	},
		        	machines:data.machines	
				})
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
			
			layer.close(loading);
		},
		error:function(){
			layer.close(loading);
		}
	});
}
function showMachineChart(mName,item){
	layer.open({
		type:1,
		title:mName+' - '+item,
		content:$('#machine-chart'),
		area:['90%', '400px'],
		offset: 'b',
		anim :2,
		resize :false,
		isOutAnim:false,
		move: false,
		cancel: function(index, layero){ 
			if(machineChart != null){
				machineChart.clear();
			}
		    layer.close(index);
		}   
	})
}
/**
 * 获取cpuload数据并绘制图表
 */
function drawCpuloadChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/cpu/load',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			console.log('cpuload data:%o',rtn);
			if(!rtn.error){
				var data = rtn.data;
				var series = [];
				var legendData = [];
				for(var name in data.yAxis){
					var yaxi = data.yAxis[name];
					var yData = [];
					if(yaxi != null){
						yaxi.reverse();
						for(var i in yaxi){
							yData.push(yaxi[i]);
						}
					}
					series.push({
						name:name,
						type:'line',
						data:yData
					});
					legendData.push(name);
				}
				data.xAxis.reverse();
				for(var i in data.xAxis){
					var date = new Date(data.xAxis[i] * 1000); 
					data.xAxis[i] = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('/')
									+" " +[date.getHours(),date.getMinutes(),date.getSeconds()].join(':');				
				}
				
				
				
				var option = {
						legend: {
						        data:legendData,
						        x: 'left'
						    },
					    tooltip : {
					    	
					        trigger: 'axis',
					        axisPointer: {
					            type: 'cross',
					            animation: false,
					            label: {
					                backgroundColor: '#505765'
					            }
					        }
					    },
					    dataZoom: [{
					    	start: 0,
					        end: 10,
					        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					        handleSize: '80%',
					        handleStyle: {
					            color: '#fff',
					            shadowBlur: 3,
					            shadowColor: 'rgba(0, 0, 0, 0.6)',
					            shadowOffsetX: 2,
					            shadowOffsetY: 2
					        }
					    }],
					    xAxis: {
					        type: 'category',
					        data:data.xAxis
					    },
					    yAxis: {
					        type: 'value',
					    },
					    series: series,
					};
				machineChart.setOption(option);
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
		}
	});
}

function drawMemoryUsageChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/memory/usage',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			console.log("memroy usage:%o",rtn);
			if(!rtn.error){
				var data = rtn.data;
				var series = [];
				data.yAxis.reverse();
				series.push({
					name:'使用',
					type:'line',
					data:data.yAxis
				});
				var unit = '';
				for(var i in data.yAxis){
					if(data.yAxis[i] != null){
						unit = 'GB';
						data.yAxis[i] = (data.yAxis[i]/1073741824).toFixed(2);
					}
				}
				data.xAxis.reverse();
				for(var i in data.xAxis){
					var date = new Date(data.xAxis[i] * 1000); 
					data.xAxis[i] = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('/')
									+" " +[date.getHours(),date.getMinutes(),date.getSeconds()].join(':');				
				}
				var option = {
					    tooltip : {
					    	formatter: '{a} <br/>{b} : {c} '+unit,
					        trigger: 'axis',
					        axisPointer: {
					            type: 'cross',
					            animation: false,
					            label: {
					                backgroundColor: '#505765'
					            }
					        }
					    },
					    dataZoom: [{
					    	start: 0,
					        end: 10,
					        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					        handleSize: '80%',
					        handleStyle: {
					            color: '#fff',
					            shadowBlur: 3,
					            shadowColor: 'rgba(0, 0, 0, 0.6)',
					            shadowOffsetX: 2,
					            shadowOffsetY: 2
					        }
					    }],
					    xAxis: {
					    	
					        type: 'category',
					        data:data.xAxis
					    },
					    yAxis: {
					    	name:'GB',
					        type: 'value',
					    },
					    series: series,
					};
				machineChart.setOption(option);
				
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
		}
	});
}
function drawNetTrafficChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/net/traffic',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			console.log("net traffic:%o",rtn);
			if(!rtn.error){
				var data = rtn.data;
				var series = [];
				var legendData = [];
				for(var name in data.yAxis){
					var yaxi = data.yAxis[name];
					var yData = [];
					if(yaxi != null){
						yaxi.reverse();
						for(var i in yaxi){
							yData.push((yaxi[i]/1024).toFixed(2));//bps 转为kbps
						}
					}
					series.push({
						name:name,
						type:'line',
						data:yData
					});
					legendData.push(name);
				}
				data.xAxis.reverse();
				for(var i in data.xAxis){
					var date = new Date(data.xAxis[i] * 1000); 
					data.xAxis[i] = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('/')
									+" " +[date.getHours(),date.getMinutes(),date.getSeconds()].join(':');				
				}

				var option = {
						
						legend: {
						        data:legendData,
						        x: 'left'
						    },
					    tooltip : {
					    	formatter: '{a0} : {c0} Kbps<br/> {a1} : {c1} Kbps',
					        trigger: 'axis',
					        axisPointer: {
					            type: 'cross',
					            animation: false,
					            label: {
					                backgroundColor: '#505765'
					            }
					        }
						    
					    },
					    dataZoom: [{
					    	start: 0,
					        end: 10,
					        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
					        handleSize: '80%',
					        handleStyle: {
					            color: '#fff',
					            shadowBlur: 3,
					            shadowColor: 'rgba(0, 0, 0, 0.6)',
					            shadowOffsetX: 2,
					            shadowOffsetY: 2
					        }
					    }],
					    xAxis: {
					        type: 'category',
					        data:data.xAxis
					    },
					    yAxis: {
					    	name:'Kbps',
					        type: 'value',
					    },
					    series: series,
					};
				machineChart.setOption(option);
				
			}
		}
	});
	
}
/**
 * 加载并绘制磁盘（目录：/）的图
 */
function drawDiskRootChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/disk/root',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			diskChartCommomCallback(rtn);
		}
	});
}
/**
 * 加载并绘制磁盘（目录：/adminpool）的图
 */
function drawDiskAdminPoolChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/disk/adminpool',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			diskChartCommomCallback(rtn);
		}
	});
}
/**
 * 加载并绘制磁盘（目录：/userpool）的图
 */
function drawDiskUserPoolChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/disk/userpool',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			diskChartCommomCallback(rtn);
		}
	});
}
/**
 * 加载并绘制磁盘（目录：/fileserver）的图
 */
function drawDiskFileServerChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/disk/fileserver',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			diskChartCommomCallback(rtn);
		}
	});
}
function drawDiskBootChart(machineId,beginTime,endTime){
	var loading = layer.load(1, {
		  shade: [0.5,'#fff'] //0.1透明度的白色背景
		});
	if(machineChart == null){
		machineChart = echarts.init($('.machine-chart-view')[0]);
	}
	machineChart.clear();
	$.ajax({
		url:CTX_PATH + '/console/node/detail/machine/disk/boot',
		type:'post',
		data:{
			token : $.cookie('token'),
			machineId:machineId,
			beginTime:beginTime,
			endTime:endTime
		},
		success:function(rtn){
			layer.close(loading);
			diskChartCommomCallback(rtn);
		}
	});
}
/**
 * 通用绘制磁盘图表
 */
function diskChartCommomCallback(rtn){
	console.log("disk:%o",rtn);
	if(!rtn.error){
		var data = rtn.data;
		var series = [];
		var legendData = [];
		for(var name in data.yAxis){
			var yaxi = data.yAxis[name];
			var yData = [];
			if(yaxi != null){
				yaxi.reverse();
				for(var i in yaxi){
					yData.push((yaxi[i]/1073741824).toFixed(2));//bps 转为kbps
				}
			}
			series.push({
				name:name,
				type:'line',
				stack: '总量',
				areaStyle: {normal: {}},
				data:yData
			});
			legendData.push(name);
		}
		data.xAxis.reverse();
		for(var i in data.xAxis){
			var date = new Date(data.xAxis[i] * 1000); 
			data.xAxis[i] = [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('/')
							+" " +[date.getHours(),date.getMinutes(),date.getSeconds()].join(':');				
		}

		var option = {
				
				legend: {
				        data:legendData,
				        x: 'left'
				    },
			    tooltip : {
			    	formatter: '{a0} : {c0} GB<br/> {a1} : {c1} GB',
			        trigger: 'axis',
			        axisPointer: {
			            type: 'cross',
			            animation: false,
			            label: {
			                backgroundColor: '#505765'
			            }
			        }
				    
			    },
			    dataZoom: [{
			    	start: 0,
			        end: 10,
			        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
			        handleSize: '80%',
			        handleStyle: {
			            color: '#fff',
			            shadowBlur: 3,
			            shadowColor: 'rgba(0, 0, 0, 0.6)',
			            shadowOffsetX: 2,
			            shadowOffsetY: 2
			        }
			    }],
			    xAxis: {
			        type: 'category',
			        data:data.xAxis
			    },
			    yAxis: {
			    	name:'GB',
			        type: 'value',
			    },
			    series: series,
			};
		machineChart.setOption(option);
	}else{
		console.error(rtn.msg+"("+rtn.error+")");
		layer.msg('数据加载失败')
	}
}